package com.example.fruit.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.fruit.MyApplication;
import com.example.fruit.R;
import com.example.fruit.adapter.FruitAdapter;
import com.example.fruit.bean.Fruit;
import com.example.fruit.ui.activity.AddActivity;
import com.example.fruit.ui.activity.LoginActivity;
import com.example.fruit.ui.activity.FruitDetailActivity;
import com.example.fruit.util.SPUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static android.app.Activity.RESULT_OK;


/**
 * 水果Fragment
 */

public class FruitFragment extends Fragment {
    private Activity myActivity;//上下文
    private TabLayout tabTitle;
    private RecyclerView rvfruitList;
    private FruitAdapter mfruitAdapter;
    private LinearLayout llEmpty;
    private Boolean mIsAdmin;
    private String mAccount;//账号
    private FloatingActionButton btnAdd;
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;//轮播下方指示点
    private int currentItem;
    private int oldPosition = 0; //记录上一次点的位置
    //存放图片的id
    private int[] imageIds = new int[]{R.drawable.c3, R.drawable.c2, R.drawable.c1};
    private ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService; //定时调度机制
    private String[] state = {"0","1","2","3","4","5"};
    private String[] title = {"果类", "柑类","桃类" ,"瓜类","蕉类","葡萄类"};
    private String typeId = "0";
    private List<Fruit> mfruit;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myActivity= (Activity) context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_fruit,container,false);
        tabTitle = (TabLayout)view.findViewById(R.id.tab_title);
        mViewPaper = view.findViewById(R.id.viewpager);//轮播
        rvfruitList = (RecyclerView)view.findViewById(R.id.rv_fruit_list);
        llEmpty = view.findViewById(R.id.ll_empty);
        btnAdd = (FloatingActionButton)view.findViewById(R.id.btn_add);
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        //获取控件
        initView();
        setView();
        //搜索
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("".equals(mAccount)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                }else {//已经登录
                    Intent intent = new Intent(myActivity, AddActivity.class);
                    startActivityForResult(intent,100);
                }
            }
        });return view;
    }
    /**
     * 初始化页面
     */
    private void initView() {
        mIsAdmin = (Boolean) SPUtils.get(myActivity, SPUtils.IS_ADMIN, false);
        mAccount = (String) SPUtils.get(myActivity,SPUtils.ACCOUNT,"");
        btnAdd.setVisibility(mIsAdmin? View.VISIBLE: View.GONE);
        tabTitle.setTabMode(TabLayout.MODE_SCROLLABLE);
        //设置tablayout距离上下左右的距离
       // tabTitle.setPadding(20,20,20,20);
        //为TabLayout添加tab名称
        for (int i=0;i<title.length;i++){
            tabTitle.addTab(tabTitle.newTab().setText(title[i]));
        }
        LinearLayoutManager layoutManager=new LinearLayoutManager(myActivity);
        //=1.2、设置为垂直排列，用setOrientation方法设置(默认为垂直布局)
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //=1.3、设置recyclerView的布局管理器
        rvfruitList.setLayoutManager(layoutManager);
        //==2、实例化适配器
        //=2.1、初始化适配器
        mfruitAdapter=new FruitAdapter(llEmpty,rvfruitList);
        //=2.3、设置recyclerView的适配器
        rvfruitList.setAdapter(mfruitAdapter);
        loadData();
        mfruitAdapter.setItemListener(new FruitAdapter.ItemListener() {
            @Override
            public void ItemClick(Fruit fruit) {
                boolean isAdmin = (boolean) SPUtils.get(myActivity,SPUtils.IS_ADMIN,false);
                String account = (String) SPUtils.get(myActivity,SPUtils.ACCOUNT,"");
                if ("".equals(account)) {//未登录,跳转到登录页面
                    MyApplication.Instance.getMainActivity().finish();
                    startActivity(new Intent(myActivity, LoginActivity.class));
                }else {//已经登录
                    Intent intent;
                    if (isAdmin){
                        intent = new Intent(myActivity, AddActivity.class);
                    }else {
                        intent = new Intent(myActivity, FruitDetailActivity.class);
                    }
                    intent.putExtra("fruit",fruit);
                    startActivityForResult(intent,100);
                }
            }
        });
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                typeId = state[tab.getPosition()];
                loadData();
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}
            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });
    }
    //加载数据
    private void loadData(){
        mfruit = DataSupport.where("typeId = ?",typeId).find(Fruit.class);
        if (mfruit !=null && mfruit.size()>0){
            rvfruitList.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
            mfruitAdapter.addItem(mfruit);
        }else {
            rvfruitList.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
        }
    }
    //轮播图UI界面的更新
    private void setView(){
       // mViewPaper = findViewById(R.id.viewpager);
        //显示的图片
        images = new ArrayList<ImageView>();
        for(int i = 0; i < imageIds.length; i++){
            ImageView imageView = new ImageView(myActivity);
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        adapter = new ViewPagerAdapter();
        mViewPaper.setAdapter(adapter);
        mViewPaper.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                dots.get(position).setBackgroundResource(R.drawable.dot_yes);
                dots.get(oldPosition).setBackgroundResource(R.drawable.dot_no);
                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {}
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
        });
    }

    /*定义轮播图的适配器*/
    public class ViewPagerAdapter extends PagerAdapter {
        //返回当前有效视图的个数。
        @Override
        public int getCount() {
            return images.size();
        }
        //判断instantiateItem函数所返回来的Key与一个页面视图是否是代表的同一个视图
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            view.removeView(images.get(position));
        }

        //创建指定位置的页面视图，也就是将一张图片放到容器中的指定位置
        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            view.addView(images.get(position));
            return images.get(position);
        }
    }
    /**
     * 利用线程池定时执行动画轮播
     */
    @Override
    public void onStart() {
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        //每隔2s时间，固定执行轮播任务。
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPageTask(), 2, 2, TimeUnit.SECONDS);
    }
    /**
     * 图片轮播任务,发送轮播消息
     */
    private class ViewPageTask implements Runnable{
        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);   //发送轮播消息
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            //这里不是具体的数据，而是一个轮播信号，目的是切换下一张图片
            mViewPaper.setCurrentItem(currentItem);
        }
    };

    //当切换到其他界面时，关闭后台轮播
    @Override
    public void onStop() {
        super.onStop();
        if(scheduledExecutorService != null){
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK){
            loadData();//加载数据
        }
    }
}
